package com.example.smartf.service.impl;

import com.example.smartf.model.mysql.Automaticplan;
import com.example.smartf.repository.mysql.AutomaticplanRepository;
import com.example.smartf.service.AutomaticService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class AutomaticServiceImpl implements AutomaticService {

    @Autowired
    private AutomaticplanRepository automaticplanRepository;

    @Override
    public List<Automaticplan> showall(String deviceID) {
        return automaticplanRepository.findAllByDeviceID(deviceID);
    }

    @Override
    public String addPlan(String deviceID, int hour_c, int min_c, int ec, int light, int pump_time, int fan_time) {
        Automaticplan automaticPlan = new Automaticplan();
        automaticPlan.setDeviceID(deviceID);
        automaticPlan.setHour_c(hour_c);
        automaticPlan.setMin_c(min_c);
        automaticPlan.setEc(ec);
        automaticPlan.setLight(light);
        automaticPlan.setPump_time(pump_time);
        automaticPlan.setFan_time(fan_time);
        automaticPlan.setStates(0);
        try {
            automaticplanRepository.save(automaticPlan);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

    @Override
    public String delPlan(Integer planID) {
        Automaticplan automaticPlan = automaticplanRepository.findByPlanID(planID);
        if(automaticPlan.getStates() == 1){
            return "used";
        }else {
            int res = automaticplanRepository.deleteByPlanID(planID);
            if(res == 1){
                return "success";
            }else {
                return "failed";
            }
        }
    }
}
